export class FunctionCodeProcessor {
    public static extract(code: string): string {
        // 保存当前处理的状态
        let inSingleQuote = false;
        let inDoubleQuote = false;
        let inBlockComment = false;

        const lines = code.split("\n");
        const result: string[] = [];

        for (let line of lines) {
            let processedLine = "";
            let hasCode = false; // 标记该行是否包含代码

            for (let i = 0; i < line.length; i++) {
                const char = line[i];
                const nextChar = line[i + 1];

                // 处理引号内的内容
                if (char === '"' && !inSingleQuote && !inBlockComment) {
                    inDoubleQuote = !inDoubleQuote;
                    processedLine += char;
                    hasCode = true;
                    continue;
                }
                if (char === "'" && !inDoubleQuote && !inBlockComment) {
                    inSingleQuote = !inSingleQuote;
                    processedLine += char;
                    hasCode = true;
                    continue;
                }

                // 如果在引号内，直接添加字符
                if (inSingleQuote || inDoubleQuote) {
                    processedLine += char;
                    hasCode = true;
                    continue;
                }

                // 处理块注释开始
                if (char === "/" && nextChar === "*" && !inBlockComment) {
                    inBlockComment = true;
                    i++; // 跳过 '*'
                    continue;
                }

                // 处理块注释结束
                if (char === "*" && nextChar === "/" && inBlockComment) {
                    inBlockComment = false;
                    i++; // 跳过 '/'
                    continue;
                }

                // 处理行注释
                if (char === "/" && nextChar === "/" && !inBlockComment) {
                    // 如果前面有代码，保留这个行注释
                    if (hasCode) {
                        processedLine += line.slice(i);
                    }
                    break;
                }

                // 如果不在块注释中，添加字符
                if (!inBlockComment) {
                    processedLine += char;
                    if (!hasCode && !char.match(/\s/)) {
                        hasCode = true;
                    }
                }
            }

            // 只添加非空行或包含代码的行
            if (processedLine.trim()) {
                result.push(processedLine);
            }
        }

        return result.join("\n");
    }
}

